package top.linyuxb.lycloud.gateway.starter.utils.filter;

import org.apache.commons.lang3.StringUtils;
import org.assertj.core.util.Lists;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import top.linyuxb.lycloud.common.properties.LyGatewayProperties;

import java.util.Objects;

/**
 * Created by Intellij IDEA.
 *
 * @Author: linyuxb
 * @Date: 2024/8/14 19:15
 * @Desc:
 */
public class LyGatewayCorsFilterUtil {

    public static CorsFilter buildCorsFilter(LyGatewayProperties.LyGatewayCorsConfigProperties corsConfig) {
        final CorsConfiguration config = new CorsConfiguration();
        // 1、允许cookies跨域
        if (Objects.nonNull(corsConfig.getAllowCredentials())) {
            config.setAllowCredentials(corsConfig.getAllowCredentials());
        }

        // 2、允许向该服务器提交请求的URI，*表示全部允许。。这里尽量限制来源域，比如http://xxxx:8080 ,以降低安全风险。。
        if (StringUtils.isNotBlank(corsConfig.getAllowedOrigins())) {
            String[] allowedOrigins = corsConfig.getAllowedOrigins().split(",");
            config.setAllowedOriginPatterns(Lists.newArrayList(allowedOrigins));
        }
        // 3、允许访问的头信息,*表示全部 com.cxl.rc.smart.config.setMaxAge(18000L);
        if (StringUtils.isNotBlank(corsConfig.getAllowedHeaders())) {
            String[] headers = corsConfig.getAllowedHeaders().split(",");
            for (String header : headers) {
                config.addAllowedHeader(header);
            }
        }

        // 4、允许提交请求的方法，*表示全部允许，也可以单独设置GET、PUT等 com.cxl.rc.smart.config.addAllowedMethod("HEAD");
        if (StringUtils.isNotBlank(corsConfig.getAllowedMethods())) {
            String[] methods = corsConfig.getAllowedMethods().split(",");
            for (String method : methods) {
                config.addAllowedMethod(method);
            }
        }
        // 5、预检请求的缓存时间（秒），即在这个时间段里，对于相同的跨域请求不会再预检了
        if (Objects.nonNull(corsConfig.getMaxAge()) && corsConfig.getMaxAge() > 0L) {
            config.setMaxAge(corsConfig.getMaxAge());
        }

        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }
}
